package com.abu.message.listener;


import cn.hutool.core.util.PhoneUtil;
import cn.hutool.core.util.StrUtil;
import com.abu.common.exception.CRException;
import com.abu.message.utils.CodeUtil;
import com.abu.message.utils.QQMailTemplate;
import com.abu.message.utils.SmsTemplate;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class PhoneMessageRabbitmqListener {


    //    手机号
    private static final String PHONE_CODE_EXCHANGE = "PHONE_CODE_EXCHANGE";
    private static final String PHONE_CODE_ROUTING = "CODE_PHONE";
    private static final String PHONE_CODE_QUEUE = "PHONE_CODE_ROUTING";


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private static final String REGISTER_PHONE = "PHONE_LOGIN.CODE.";


    /**
     * 发送验证码到手机号中
     *
     * @param phone
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = PHONE_CODE_QUEUE, ignoreDeclarationExceptions = "true"),
            exchange = @Exchange(name = PHONE_CODE_EXCHANGE, ignoreDeclarationExceptions = "true", type = "topic"),
            key = {PHONE_CODE_ROUTING}
    ))
    public void sendMsgToPhone(String phone) {
//        生成验证码
        String code = CodeUtil.generator(4);
//        发送验证码到手机号
        Integer httpStatus = null;
        try {
            httpStatus = SmsTemplate.sendMsg(phone, code);
        } catch (ClientException e) {
            log.info("发送短信失败：{}", e.getMessage());
        }
        if (httpStatus == 200) {
            this.stringRedisTemplate.opsForValue().set(REGISTER_PHONE + phone, code, 5, TimeUnit.MINUTES);
        }
//        缓存中保存一份验证码
    }


}
